package com.example;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


public class test08http extends Activity {

    private TextView tv;
    private ProgressDialog pd;
    private DBHelper dbHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.textView01);
       // dbTest();
        new AsyncGetLifeData().execute(getResources().getString(R.string.InputParamValueLifeCode), "9616774", "0852");
    }

    private void dbTest() {
        dbHelper = new DBHelper(this);
        //long l = dbHelper.createRecord("025", "7369168", "54321");

        // Get all of the notes from the database and create the item list
        Cursor c = dbHelper.fetchAll();
        startManagingCursor(c);
        String[] from = new String[]{DBHelper.KEY_CODE, DBHelper.KEY_PHONE};
        int[] to = new int[]{android.R.id.text2, android.R.id.text1};

        // Now create an array adapter and set it to display using our row
        ListView lv = (ListView)findViewById(R.id.listView);
        SimpleCursorAdapter notes =
                new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, from, to);
        lv.setAdapter(notes);

    }

    private void showDialog(String message) {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }

        pd = ProgressDialog.show(this, "Working...", message, true, false);
    }


    public class AsyncGetLifeData extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            publishProgress("Connecting...");
            if (strings.length == 3) {

                HttpPost httpPost = new HttpPost(getResources().getString(R.string.IssaFormPath));
                String s;
                try {
                    HttpClient httpclient = getClient();
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                    nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNameCode), strings[0]));
                    nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNamePhone), strings[1]));
                    nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNamePassword), strings[2]));
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httpPost, new BasicHttpContext());
                    publishProgress("Reading data...");
                    s = ResponseToStr(response);
                    publishProgress("Preparing result...");
                    s = formatLifeData(s);

                } catch (ClientProtocolException e) {
                    s = "ClientProtocolException: " + e.getMessage() + e.toString();

                } catch (Exception e) {
                    s = "Exception: " + e.getMessage() + e.toString();

                }
                return s;
            }
            return "Error: wrong params count";
        }

        protected void onProgressUpdate(String... progress) {
            if (progress.length > 0)
                showDialog(progress[0]);
        }

        protected void onPostExecute(String result) {
            pd.dismiss();
            tv.setText(result);

        }
    }

    private String formatLifeData(String s) {

        try {
            String newLine = "\n";//getResources().getString(R.string.NewLine);
            s = Html.fromHtml(s).toString().replace("\n\n", newLine);
            // удаляем лишнюю инфу
            s = s.split(getResources().getString(R.string.ReplaceConstDate))[1]
                    .split(getResources().getString(R.string.ReplaceConstVAR))[0];

            //перегруппировка по баллансу
            String[] ss = s.split("(Баланс)|(ФИО)");

            String balance;
            String[] sb = ss[1].trim().split(newLine);
            if (sb.length > 2) {
                balance = sb[0] + ": " + sb[2] + newLine + sb[1] + ": " + sb[3];
            } else {
                balance = sb[0] + ": " + sb[1];
            }
            s = ss[0] + balance + newLine + ss[2];

            // перегруппировка в зависимости от наличия услуг
            ss = s.split(getResources().getString(R.string.Services));
            if (ss.length > 1 && ss[1].replace(newLine, "").trim().length() > 0) {
                // есть "услуги"
                s = getResources().getString(R.string.Services) + ":" + ss[1] + ss[0];
            } else {
                //нет услуг
                s = ss[0].replaceFirst(newLine, "");
            }

        } catch (Exception e) {
            s = "Exception: " + e.getMessage() + e.toString();
        }
        return s;
    }

    public String getInfoLife(String code, String phone, String pass) {
        // Create a new HttpClient and Post Header

        HttpPost httpPost = new HttpPost(getResources().getString(R.string.IssaFormPath));
        String s;
        try {
            HttpClient httpclient = getClient();
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNameCode), code));
            nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNamePhone), phone));
            nameValuePairs.add(new BasicNameValuePair(getResources().getString(R.string.InputParamNamePassword), pass));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httpPost, new BasicHttpContext());

            s = ResponseToStr(response);
            s = formatLifeData(s);

        } catch (ClientProtocolException e) {
            s = "ClientProtocolException: " + e.getMessage() + e.toString();

        } catch (Exception e) {
            s = "Exception: " + e.getMessage() + e.toString();

        }
        return s;
    }

    public static DefaultHttpClient getClient() {
        DefaultHttpClient ret = null;

        //sets up parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);

        //registers schemes for both http and https
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        ret = new DefaultHttpClient(manager, params);
        return ret;
    }

    public static String ResponseToStr(HttpResponse response) {
        String result = "";
        try {
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line + "\n");
            }
            in.close();
            result = str.toString();
        } catch (Exception ex) {
            result = "Exception: " + ex.getMessage() + ex.toString();
        }
        return result;
    }

}
